package com.thm.tfast.modules.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thm.tfast.core.enums.LogTypeEnum;
import com.thm.tfast.core.exception.Asserts;
import com.thm.tfast.core.sevruity.domain.SysUserDetails;
import com.thm.tfast.core.utils.SecurityUtil;
import com.thm.tfast.modules.sys.mapper.SysLogMapper;
import com.thm.tfast.modules.sys.model.SysLog;
import com.thm.tfast.modules.sys.model.SysUser;
import com.thm.tfast.modules.sys.model.vo.log.LogVo;
import com.thm.tfast.modules.sys.service.SysLogService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 日志表 服务实现类
 * </p>
 *
 * @author THM
 * @since 2022-10-31
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {

    @Override
    public Page<LogVo> page(String keyword, Integer type, Integer pageNum, Integer pageSize) {
        Page<LogVo> page = new Page<>(pageNum,pageSize);
        List<LogVo> logVos = this.baseMapper.page(keyword, type, page);
        page.setRecords(logVos);
        return page;
    }

    @Override
    public LogVo getLogById(Long logId) {
        return this.baseMapper.getLogById(logId);
    }

    @Override
    public SysLog createSysLog(List<Object> args, Long userId) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest();
        SysLog sysLog = new SysLog();
        sysLog.setType(LogTypeEnum.NORMAL.getCode());
        sysLog.setIp(ServletUtil.getClientIP(request));
        sysLog.setUrl(URLUtil.getPath(request.getRequestURI()));
        sysLog.setMethod(request.getMethod());
        sysLog.setAgent(request.getHeader("user-agent"));
        if (CollectionUtil.isNotEmpty(args)){
            sysLog.setParams(JSONUtil.toJsonStr(args));
        } else {
            sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
        }
        if (Objects.isNull(userId)){
            SysUserDetails currentUser = SecurityUtil.getCurrentUser();
            sysLog.setCreateUser(currentUser.getUserId());
            sysLog.setCreateTime(currentUser.getDate());
        } else {
            sysLog.setCreateUser(userId);
            sysLog.setCreateTime(new Date());
        }
        return sysLog;
    }
}
